import 'package:flutter/material.dart';
import 'package:ichinesereader/models/report/chartData.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
import 'package:intl/intl.dart';

class SplineAreaChart extends StatelessWidget {
  SplineAreaChart({
    Key? key,
    required this.title,
    required this.splineAreaChartData,
    this.axisTitle = "Times",
    this.isYear = true,
  }) : super(key: key);

  final String title;
  final String axisTitle;
  final bool isYear;

  final List<List<SplineAreaChartData>> splineAreaChartData;

  @override
  Widget build(BuildContext context) {
    Log.debug('build SplineAreaChart');

    return _buildDefaultAreaChart();
  }

  /// Returns the default cartesian area chart.
  SfCartesianChart _buildDefaultAreaChart() {
    return SfCartesianChart(
      legend: Legend(
          overflowMode: LegendItemOverflowMode.wrap,
          isResponsive: true,
          isVisible: true,
          toggleSeriesVisibility: true,
          position: LegendPosition.top),
      title: ChartTitle(text: title),
      plotAreaBorderWidth: 0,
      primaryXAxis: CategoryAxis(),
      primaryYAxis: NumericAxis(
          labelFormat: '{value}',
          title: AxisTitle(text: axisTitle),
          interval: 1,
          axisLine: const AxisLine(width: 0),
          majorTickLines: const MajorTickLines(size: 0)),
      series: _getDefaultAreaSeries(),
      tooltipBehavior: TooltipBehavior(enable: true),
    );
  }

  /// Returns the list of Chart series
  /// which need to render on the default area chart.
  List<AreaSeries<SplineAreaChartData, String>> _getDefaultAreaSeries() {
    var areadatas = splineAreaChartData
        .map((chartData) => AreaSeries<SplineAreaChartData, String>(
              dataSource: chartData,
              opacity: 0.7,
              name: '${chartData[0].year}',
              xValueMapper: (SplineAreaChartData data, _) => isYear
                  ? DateFormat.MMM()
                      .format(new DateTime(data.year, data.month!))
                  : data.month.toString(),
              yValueMapper: (SplineAreaChartData data, _) => data.count,
            ))
        .toList();
    return areadatas;
  }
}
